import axios from "axios";


const ajax = axios;
//因为前端是通过反向代理与后端服务器进行衔接，因此，每个请求的地址都有一个统一的前缀
//这个前缀如果在每一个请求中去添加，无疑是很费事儿的，所以我们考虑使用拦截器来做统一的
//处理
ajax.interceptors.request.use(config => {//请求的拦截器
    //为每一个请求的地址统一添加前缀
    config.url = "/electronic" + config.url
    return config;
}, error => Promise.reject(error))

export function doGet(url, data, callback){
    ajax({
        url: url,
        params: data,
        method: 'GET'
    }).then(resp => {
        if(typeof callback === "function"){
            callback(resp.data)
        }
    }).catch(error => {

    }).finally(_ =>{

    });
}

export function doLogin(url, data, callback){
    ajax({
        url: url,
        data: data,
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(resp => {
        if(typeof callback === "function"){
            callback(resp.data)
        }
    }).catch(error => {

    }).finally(_ =>{

    });
}

export function doPost(url, data, callback){
    ajax({
        url: url,
        data: data,
        method: 'POST'
    }).then(resp => {
        if(typeof callback === "function"){
            callback(resp.data)
        }
    }).catch(error => {

    }).finally(_ =>{

    });
}

export function doPut(url, data, callback){
    ajax({
        url: url,
        data: data,
        method: 'PUT'
    }).then(resp => {
        if(typeof callback === "function"){
            callback(resp.data)
        }
    }).catch(error => {

    }).finally(_ =>{

    });
}

export function doDelete(url, data, callback){
    let parameterInfo = "";
    if(data)
        Object.keys(data).forEach(key => parameterInfo += key + '=' + data[key] + "&")
    ajax({
        url: url + "?" + parameterInfo,
        params: {},
        method: 'DELETE'
    }).then(resp => {
        if(typeof callback === "function"){
            callback(resp.data)
        }
    }).catch(error => {

    }).finally(_ =>{

    });
}

export function uploadFile(url, file, callback){
    const formData = new FormData();
    formData.append("file", file)
    ajax({
        url: url,
        data: formData,
        method: 'POST',
        headers: {'Content-Type': 'multipart/form-data'}
    }).then(resp => {
        if(typeof callback === "function"){
            callback(resp.data)
        }
    }).catch(error => {

    }).finally(_ =>{

    });
}
